# -*- coding: utf-8 -*-
import math
import os
import time
import GCL
import json
import subprocess
from pynput.mouse import Button, Controller
from pynput.keyboard import Key, Controller as KeyCtroler

mouse = Controller()
keyboard = KeyCtroler()

import tkinter as tk
_root = tk.Tk()
screenwidth = _root.winfo_screenwidth()
screenheight = _root.winfo_screenheight()
_root.destroy()


originAlpha = 0
originBeta = 0
originGamma = 0
last_key_time = 0


def openfile(fpath):
    subprocess.call(["open", fpath])

# 手机位置消息的入口
def onMsg(ws, msg):
    # 位置信息
    if "rt" in msg:
        rt = msg["rt"]
        onOrientation(rt[0], rt[1], rt[2])
    # 点击信息
    elif 'btn' in msg:
        onButton(msg['btn'], msg['act'])
    elif 'local' in msg:
        print("dmclient 启动过成功：%s" % msg['local'])
    elif 'act' in msg:
        # GCL.showInfo(msg)
        if 'auth'==msg['act']:
            GCL.destid = msg['from']
            resp = {
                "act": "auth_resp",
                "info": GCL.destid,
                "from": GCL.clientid
            }
            ws.send(json.dumps(resp))
    elif 'getlist' in msg:
        workingdir = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop')
        path = os.path.join(workingdir, msg['getlist'])
        FILETYPES = ["ppt","pptx","doc","docx","xls","xlsx","mp4","mp3"]
        files = []
        for fname in os.listdir(path):
            if fname.startswith("."):
                continue
            print(fname)
            ext = fname.split(".")[-1].lower()
            print(ext)
            # if ext in FILETYPES:
            files.append(fname)
            print(len(files))

        resp = {
            "info": GCL.destid,
            "from": GCL.clientid,
            'getlist_resp': path,
            "list": files
        }
        ws.send(json.dumps(resp))
    elif "playfile" in msg:
        workingdir = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop')
        fpath = os.path.join(workingdir, msg['playfile'])
        p = subprocess.Popen(["open", fpath])
        print("playfile (%d)-%s"%(p.pid, fpath))

        resp = {
            "info": GCL.destid,
            "from": GCL.clientid,
            'playfile_resp': msg['playfile'],
            "pid": p.pid
        }
        ws.send(json.dumps(resp))

        # 让程序全屏运行
        ext = fpath.split(".")[-1].lower()
        GCL.queueText.put("fullscreen %s"%ext)


def onOrientation(alpha, beta, gamma):
    KEY_TIME_GAP = 1
    global last_key_time

    # 水平即鼠标模式；侧立则脱离鼠标模式；翻过来，则手势模式
    # 处理手势按键
    now = time.time()
    if beta > -90 and beta < -30:  # 下翻
        if now - last_key_time < KEY_TIME_GAP:  # 按键事件不要相隔太近
            return
        last_key_time = now
        keyboard.press(Key.page_down)
        keyboard.release(Key.page_down)
        return
    elif beta < 90 and beta > 75:  # 上翻
        if now - last_key_time < KEY_TIME_GAP:  # 按键事件不要相隔太近
            return
        last_key_time = now
        keyboard.press(Key.page_up)
        keyboard.release(Key.page_up)
        return

    # 平放时的鼠标移动事件
    elif math.fabs(gamma) < 35:  # 水平
        if originAlpha == 0 and originBeta==0 and originGamma==0:
            # resetMouse(alpha,beta,gamma)  
            resetMouse(alpha,0,gamma)  # 20210419，改为水平位置对应屏幕上下中间
            return
        mouseMove(alpha, beta, gamma)
        return

    # 左侧立事件
    elif math.fabs(math.fabs(gamma)-90) < 20:  # 左侧立
        if mouse.position == (screenwidth / 2, screenheight / 2):
            return
        # resetMouse(alpha,beta,gamma)
        resetMouse(alpha, 0, gamma)   # 20210419，改为水平位置对应屏幕上下中间
        return


def resetMouse(alpha, beta, gamma):
    global originBeta, originAlpha, originGamma
    originAlpha = alpha
    originBeta = beta
    originGamma = gamma
    mouse.position = (screenwidth / 2, screenheight / 2)

def mouseMove(alpha, beta, gamma):
    mousex = 0
    mousey = 0

    # alpha的取值范围是[360~0]，代表鼠标的左右移动
    dx = - (alpha - originAlpha)
    if dx < 180:  # 向右
        mousex = dx
    elif dx < 0:
        mousex = -1 * dx
    elif dx > 180:
        mousex = 360 - dx

    # beta的取值范围是[180~-180]，代表鼠标的上下移动
    dy = -(beta - originBeta)
    if dy < 180:  # 向右
        mousey = dy
    elif dy < 0:
        mousey = -1 * dy
    elif dy > 180:
        mousey = 360 - dy

    # 太小的变化，不要晃动鼠标
    LINGMINDU = 0.5
    if math.fabs(mousex) < LINGMINDU and math.fabs(mousey) < LINGMINDU:
        return

    w = screenwidth / 2
    h = screenheight / 2

    mouse.position = (w + 4 * w * mousex / 180, h + 4 * h * mousey / 180)

def onButton(btn, act):
    if 'mouseleft'==btn:
        if 'down'==act:
            mouse.press(Button.left)
        elif 'up'==act:
            mouse.release(Button.left)
        else:
            mouse.press(Button.left)
            mouse.release(Button.left)
    elif 'mouseright'==btn:
        if 'down'==act:
            mouse.press(Button.right)
        if 'up'==act:
            mouse.release(Button.right)
    elif 'wheelup'==btn:
        mouse.release(Button.wheelup)
    elif 'wheeldown'==btn:
        mouse.release(Button.wheeldown)
    elif 'enter'==btn:
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)
    elif 'space'==btn:
        keyboard.press(Key.space)
        keyboard.release(Key.space)
    elif 'volumnup'==btn:
        keyboard.press(Key.media_volume_up)
        keyboard.release(Key.media_volume_up)
    elif 'volumndown'==btn:
        keyboard.press(Key.media_volume_down)
        keyboard.release(Key.media_volume_down)
    elif 'pageup'==btn:
        keyboard.press(Key.page_up)
        keyboard.release(Key.page_up)
    elif 'pagedown'==btn:
        keyboard.press(Key.page_down)
        keyboard.release(Key.page_down)
    elif 'left'==btn:
        keyboard.press(Key.left)
        keyboard.release(Key.left)
    elif 'right'==btn:
        keyboard.press(Key.right)
        keyboard.release(Key.right)
    elif 'F5'==btn:
        keyboard.press(Key.f5)
        keyboard.release(Key.f5)
    elif 'esc'==btn:
        keyboard.press(Key.esc)
        keyboard.release(Key.esc)
    elif 'ctrl_tab'==btn:
        keyboard.press(Key.cmd)
        keyboard.press(Key.tab)
        keyboard.release(Key.tab)
        keyboard.release(Key.cmd)
    elif 'playppt'==btn:
        keyboard.press(Key.cmd)
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)
        keyboard.release(Key.cmd)
    elif 'closewin'==btn:
        keyboard.press(Key.cmd)
        keyboard.press('q')
        keyboard.release('q')
        keyboard.release(Key.cmd)
    elif 'fullscreen'==btn:
        keyboard.press(Key.cmd)
        keyboard.press(Key.ctrl)
        keyboard.press('f')
        keyboard.release('f')
        keyboard.release(Key.ctrl)
        keyboard.release(Key.cmd)
    else:
        print("未知动作")  #为了安全起见，不应允许随意输入其它按键

def playHotKey(ext):
    print("playhotkey %s" % ext)
    if ext in ['ppt', 'pptx']:
        keyboard.press(Key.cmd)
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)
        keyboard.release(Key.cmd)
    elif ext in ['mp4']:
        keyboard.press(Key.space)
        keyboard.release(Key.space)
